package com.cn.wanxi.consumer.listener;

import com.cn.wanxi.consumer.domain.entity.User;
import com.cn.wanxi.consumer.mapper.UserMapper;
import com.cn.wanxi.consumer.service.IUserService;
import com.cn.wanxi.consumer.util.ParamUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @ClassName UserListener
 * @Description 用户消息队列的监听器
 * @Author JiJiang
 * @Date 2022/9/28 16:57
 * @Version 1.0
 */

@Slf4j
@Component
public class UserListener {

    @Autowired
//    private IUserService userService;
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = ParamUtil.QUEUE_NAME_REGISTER) //指定该监听器绑定的队列名
            , exchange = @Exchange(name = ParamUtil.EXCHANGE_NAME_USER, type = ExchangeTypes.TOPIC)
            , key = {ParamUtil.BINDING_KEY_NAME}
    ))
    public void userRegisterQueReceive(User user) {
        System.out.println("需要添加的用户名：" + user.getUsername());
        int affectedRow = userMapper.insert(user);

        if (affectedRow > 0) {
            Long id = user.getId();
            String username = user.getUsername();
            redisTemplate.opsForValue().set(ParamUtil.REDIS_REGISTER_USERNAME_PREFIX + username, id);
        }

        System.out.println("用户\t" + user.getUsername() + "\t添加" + (affectedRow > 0 ? "成功" : " 失败 "));

    }

}
